package com.thinkersre.controller;

import com.alibaba.fastjson2.JSONObject;
import com.thinkersre.entity.Message;
import com.thinkersre.entity.Page;
import com.thinkersre.entity.User;
import com.thinkersre.service.MessageService;
import com.thinkersre.service.UserService;
import com.thinkersre.util.HostHolder;
import com.thinkersre.util.ThinkersReConstant;
import com.thinkersre.util.ThinkersReUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.util.*;

@Controller
public class MessageController implements ThinkersReConstant {
    @Resource
    private MessageService messageService;
    @Resource
    private HostHolder hostHolder;
    @Resource
    private UserService userService;
    //私信列表
    @GetMapping("/letter/list")
    public String getLetterList(Model model, Page page){

        User user = hostHolder.getUser();
        //分页信息
        page.setPageSize(5);
        page.setPath("/letter/list");
        page.setRowsTotal(messageService.findConversationCount(user.getId()));
        //会话列表
        List<Message> conversationList = messageService.findConversations(user.getId(), page.getOffset(), page.getPageSize());
        List<Map<String,Object>> conversations = new ArrayList<>();
        if(conversationList!=null){
            for (Message message : conversationList){
                Map<String,Object> map = new HashMap<>();
                map.put("message",message);
                map.put("letterCount",messageService.findLetterCount(message.getConversationId()));
                map.put("unreadCount",messageService.findLetterUnreadCount(user.getId(), message.getConversationId()));
                //传入自己的账号类型
//                map.put("userType",user.getType());
                int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
                map.put("target",userService.findUserById(targetId));

                conversations.add(map);
            }
        }
        model.addAttribute("conversations",conversations);
        model.addAttribute("userType",user.getType());
        //查询未读消息数量
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);

        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);

        return"/site/letter";

    }



    @GetMapping("/letter/detail/{conversationId}")
    public String getLetterDeatil(@PathVariable("conversationId")String conversationId, Page page,Model model){
        //分页信息
        page.setPageSize(5);
        page.setPath("/letter/detail/"+conversationId);
        page.setRowsTotal(messageService.findLetterCount(conversationId));
        //私信列表
        List<Message> letterList = messageService.findLetters(conversationId, page.getOffset(), page.getPageSize());
        List<Map<String,Object>> letters = new ArrayList<>();
        //对letterlist进行判断，非空则遍历
        if(letterList != null){
            for (Message message:letterList){
                Map<String,Object> map = new HashMap<>();
                map.put("letter",message);
                map.put("fromUser",userService.findUserById(message.getFromId()));
                letters.add(map);

            }
        }

        model.addAttribute("letters",letters);
        //放入当前使用的账号id
        model.addAttribute("originUserId",hostHolder.getUser().getId());
        //私信目标
        model.addAttribute("target",getLetterTarget(conversationId));

        //设置已读
        List<Integer> ids = getLetterIds(letterList);
        if(!ids.isEmpty()){
            messageService.readMesssge((ids));
        }

        return "/site/letter-detail";
    }


    private User getLetterTarget(String conversationId){
        String[] split = conversationId.split("_");
        int id0 = Integer.parseInt(split[0]);
        int id1 = Integer.parseInt(split[1]);

        if(hostHolder.getUser().getId() == id0){
            return userService.findUserById(id1);
        }else{
            return userService.findUserById(id0);
        }

    }

    private List<Integer> getLetterIds(List<Message> letterList){
        List<Integer> ids = new ArrayList<>();
        //如果不为空，进行遍历
        if (letterList!=null){
            for (Message message:letterList){
                if(hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0){
                    ids.add(message.getId());
                }
            }
        }

        return ids;
    }

    //发送私信
    @PostMapping("/letter/send")
    @ResponseBody
    public String sendLetter(String toName,String content){
//        Integer.valueOf("abc");//测试
        User target = userService.findUserByName(toName);
        if(target == null){
            return ThinkersReUtil.getJSONString(1,"目标用户不存在");
        }
        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        if(message.getFromId()<message.getToId()){
            message.setConversationId(message.getFromId()+"_"+message.getToId());
        }else{
            message.setConversationId(message.getToId()+"_"+message.getFromId());
        }

        message.setContent(content);
        message.setCreateTime(new Date());
        messageService.addMessage(message);
        return ThinkersReUtil.getJSONString(0);
    }

    //通知类
    //SuperAdmin发送全局通知
    @PostMapping("/notice/send")
    @ResponseBody
    public String sendNotice(String content){
        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(0);
        message.setConversationId("0_"+hostHolder.getUser().getId());
        message.setContent(content);
        message.setCreateTime(new Date());
        messageService.addMessage(message);
        return ThinkersReUtil.getJSONString(0);
    }
    //通知列表
    @GetMapping("/notice/list")
    public String getNoticeList(Model model){
        User user = hostHolder.getUser();
        //查询评论类通知
        Message message = messageService.findLatestNotice(user.getId(), TOPIC_COMMENT);
        if(message!=null){
            Map<String,Object> messageMap = new HashMap<>();
            messageMap.put("message",message);
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);
            messageMap.put("user",userService.findUserById((Integer) data.get("userId")));
            messageMap.put("entityType",data.get("entityType"));
            messageMap.put("entityId",data.get("entityId"));
            messageMap.put("postId",data.get("postId"));
            messageMap.put("conversationId",message.getConversationId());
            int count = messageService.findNoticeCount(user.getId(), TOPIC_COMMENT);
            messageMap.put("count",count);
            int unread = messageService.findNoticeUnreadCount(user.getId(),TOPIC_COMMENT);
            messageMap.put("unread",unread);
            model.addAttribute("commentNotice",messageMap);
        }

        //查询点赞类通知
        message = messageService.findLatestNotice(user.getId(), TOPIC_LIKE);

        if(message!=null){
            Map<String,Object> messageMap = new HashMap<>();
            messageMap.put("message",message);
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);
            messageMap.put("user",userService.findUserById((Integer) data.get("userId")));
            messageMap.put("entityType",data.get("entityType"));
            messageMap.put("entityId",data.get("entityId"));
            messageMap.put("postId",data.get("postId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_LIKE);
            messageMap.put("count",count);
            int unread = messageService.findNoticeUnreadCount(user.getId(),TOPIC_LIKE);
            messageMap.put("unread",unread);
            model.addAttribute("likeNotice",messageMap);
        }

        //查询关注类通知
        message = messageService.findLatestNotice(user.getId(), TOPIC_FOLLOW);
        if(message!=null){
            Map<String,Object> messageMap = new HashMap<>();
            messageMap.put("message",message);
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);
            messageMap.put("user",userService.findUserById((Integer) data.get("userId")));
            messageMap.put("entityType",data.get("entityType"));
            messageMap.put("entityId",data.get("entityId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_FOLLOW);
            messageMap.put("count",count);
            int unread = messageService.findNoticeUnreadCount(user.getId(),TOPIC_FOLLOW);
            messageMap.put("unread",unread);
            model.addAttribute("followNotice",messageMap);

        }

        //查询系统类通知
        message = messageService.findLatestNotice(user.getId(), TOPIC_SYSTEM);
        if(message!=null){
            Map<String,Object> messageMap = new HashMap<>();
            messageMap.put("message",message);
            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);
            messageMap.put("user",userService.findUserById((Integer) data.get("userId")));
            messageMap.put("entityType",data.get("entityType"));
            messageMap.put("entityId",data.get("entityId"));

            int count = messageService.findNoticeCount(user.getId(), TOPIC_SYSTEM);
            messageMap.put("count",count);
            int unread = messageService.findNoticeUnreadCount(user.getId(),TOPIC_SYSTEM);
            messageMap.put("unread",unread);
            model.addAttribute("systemNotice",messageMap);

        }

        //查询未读消息数量
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);
        int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);


        return "/site/notice";
    }




    //通知详情（确认已读）
    @GetMapping("/notice/detail/{topic}")
    public String getNoticeDetail(@PathVariable("topic")String topic,Page page,Model model){
        User user = hostHolder.getUser();
        page.setPageSize(5);
        page.setPath("/notice/detail/"+topic);
        page.setRowsTotal(messageService.findNoticeCount(user.getId(), topic));

        List<Message> noticeList = messageService.findNotices(user.getId(), topic, page.getOffset(), page.getPageSize());
        List<Map<String, Object>> noticeMapList = new ArrayList<>();
        if (noticeList!=null){
            for (Message notice:noticeList){
                Map<String,Object> map = new HashMap<>();
                //通知
                map.put("notice",notice);
                //内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                //把json字符串转为一个map对象，最终得到的data对象是一个包含了JSON字符串中所有键值对的HashMap对象
                Map<String,Object> data = JSONObject.parseObject(content,HashMap.class);
                //发起事件的user
                map.put("user",userService.findUserById((Integer) data.get("userId")));
                map.put("entityType",data.get("entityType"));
                map.put("entityId",data.get("entityId"));
                map.put("postId",data.get("postId"));
                //通知作者
                map.put("fromUser",userService.findUserById(notice.getFromId()));
                noticeMapList.add(map);
            }
        }
        model.addAttribute("notices",noticeMapList);
        //设置已读
        List<Integer> ids = getLetterIds(noticeList);
        if(!ids.isEmpty()){
            messageService.readMesssge(ids);
        }

        return "forward:/notice/list";

    }

    //通知详情
//    @GetMapping("/notice/detail/{topic}/{conversationId}")
//    public String getNoticeDetailByConversationId(@PathVariable("conversationId")String conversationId
//                                                  ){
//
//
//
//        return "/site/discuss-detail";
//    }






}